<?php
namespace Common\Model;

use Think\Model;
use Think\Model\RelationModel;
class CrmCustomContactModel extends RelationModel
{

    protected $_auto = array(
//        array('model', 'arr2str', self::MODEL_BOTH, 'function'),
//        array('model', null, self::MODEL_BOTH, 'ignore'),
//        array('extend', 'json_encode', self::MODEL_BOTH, 'function'),
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('state', '0', self::MODEL_BOTH),
    );

    public function update($data)
    {
        return empty($data['id']) ? $this->add($data) : $this->save($data);
    }

    public function delete($id)
    {
        $data['state'] = -1;
        $result = $this->where('id=%d', $id)->save($data);
        if ($result) {
            return true;
        }
        return false;
    }

    public function get($id)
    {
        $condition = array();
        $condition['id'] = array('eq', $id);
        $condition['state'] = array('egt', 0);
        $model = $this->field(true)->where($condition)->find();
        return $model;
    }

    public function accumulation_follow_times($phone)
    {
        $row = $this->where('phone="%s" or tel="%s"', $phone, $phone)->setInc('follow_times', 1);
        return $row;
    }

    public function get_list($page_no = 1, $page_size = 0)
    {
        $condition = array();
        $condition['state'] = array('egt', 0);

        $count = 0;
        $expression = $this->where($condition);
        if ($page_size > 0) {
            $expression = $expression->limit(($page_no - 1) * $page_size, $page_size);
            $count = $expression->count();
        }
        $list = $this->where($condition)->select();
        return [$list, $count];
    }


//    private function assembleCondition($name, $state)
//    {
//        $condition = array();
//        if (!empty($key)) {
//            $key_param['name'] = array('like', '%' . $name . '%');
//        }
//
//        if (!empty($state)) {
//            $condition['state'] = $state;
//        } else {
//            $condition['state'] = array('neq', -1);
//        }
//
//        return $condition;
//    }

}